import fetch from '@/config/fetch'
import { tps, mdm, shop, order, snxd } from '@/config/env'
import router from '@/router/index'


export default {
	state: {
		cart2Info: '',
		centerCart2Info: '',
		invalidItems: null,
		volumeinfo: [],
		couponList: [],
		Alldata:[],
		centerAlldata:[],
		cart2No:'',
		centervolumeinfo:[],
		fromCoupon: false,
		stationList: {}
	},
	mutations: {
		updateCart2 (state, info) {
			state.cart2Info = info
		},

		centerCart2Info (state, info) {
			state.centerCart2Info = info
		},

		updateInvalidItems2(state, info) {
			state.invalidItems = info;
		},

		clearvolumeinfo(state, info) {
			state.volumeinfo = [];
		},//清除优惠卷为，目的是从车一来的时候需要从新刷新所有接口，从优惠卷则不需要刷新接口

		//是否从优惠券进入
		updateFromCoupon(state, status) {
			state.fromCoupon = status;
		},
		// 存储自提点
		updateStationList(state, info) {
			state.stationList = info || [];
		}
	},
	 
	actions: {
		// 获取小店车2
		getCart2 ({dispatch, commit, state, rootState }, options) {
			let params = {
				app: 'wap',
				appVersion: '3.2.2',
				cityId: rootState.position.cityCode,
				operationStoreCode: rootState.position.storeLocation,
				poiId: rootState.position.poiId,
				areaId: rootState.position.areaId
			}
			fetch({
				url: tps + '/app/cart2/private/showCartInfo.do',
				params: params,
				jsonp: 'callBack'
			}).then((info) => {
				commit('showMask', false)
				if(info.code==1){
					if(options == 1) {
						 //这里主要取优惠卷的信息
						var data = info.data;
						if(data && data.couponUseInfos && data.couponUseInfos.length > 0) {
							state.volumeinfo = data.couponUseInfos //将正在使用的优惠卷的信息保存到volumeinfo
						}else {
							state.volumeinfo = {length: '-1'}
						}
					}
					commit('updateCart2', info.data)

					// 如果支持自提，请求自提点列表
					info.data.deliveryInfo.canPickUp&&dispatch('storeStationList');
				}else{
					AlertBox({type: 'mini',msg: info.msg})
				}
			});
		},
		// 获取自提点信息
		storeStationList({state, commit, rootState}){
			let type = state.cart2Info.cartHeadBasicInfo.orderType
			fetch({
				url: snxd + '/storeInfo/queryStoreStationList.do',
				params: {
					areaId: rootState.position.areaId,
					poiId: rootState.position.poiId,
					source: 'wap',
					version: '3.2.2',
					storeLocation: rootState.position.storeLocation,
					orderType: type
				}
			}).then((rep) => {
				if(rep.code==1){
						//debugger
					commit('updateStationList', rep.data)
				}else{
					AlertBox({type: 'mini',msg: rep.msg})
				}
			});
		},	
		// 立即使用优惠券
		useFn ({dispatch, commit, state, rootState }) {
			var num = 0;
		 	if(state.Alldata.length == 0 )return
		 	var arr = [];
			for(var i = 0; i < state.Alldata.length; i++) {
				if(state.Alldata[i].cheack == 'cheacked') {
					num ++
					arr.push({"couponNo": state.Alldata[i].couponNumber})
				}
			}
			if(num > 6) {
				AlertBox({type: 'mini',msg: '您使用的优惠券数量超过限制，请修改'})
				return;
			}
			//dispatch('private1', arr)
			fetch({
				url: tps + '/app/cardcoupon/private/recCouponInfo.do',
				params: {
					app: 'wap',
					appVersion: '3.2.2',
					cityId: rootState.position.cityCode,
					data: JSON.stringify(arr)
				},
				type:'post'
			}).then((rep) => {
				if(rep.code==1){
						commit('updateFromCoupon', true)
						location.href="#/cart2"	
						dispatch('getCart2', 1)
				}else{
					AlertBox({type: 'mini',msg: rep.msg})
				}
			});
			// console.log(num)
		},
		centeruseFn ({dispatch, commit, state, rootState }) {
			var num = 0;
			console.log(state.centerAlldata)
		 	if(state.centerAlldata.length == 0 ){
		 		return
		 	}
		 	var arr = [];
			for(var i = 0; i < state.centerAlldata.length; i++){
				if(state.centerAlldata[i].cheack == 'cheacked') {
					num ++
					console.log(i)
					arr.push({"usedAmount":state.centerAlldata[i].amount || '',"shopCode": state.centerAlldata[i].shopCode || '',"couponType":state.centerAlldata[i].couponType || '',"couponNo":state.centerAlldata[i].couponNum || '',"oldCardType":state.centerAlldata[i].oldCouponType || ''})
				}
			}
			if(num > 6) {
				AlertBox({type: 'mini',msg: '您使用的优惠券数量超过限制，请修改'})
				return;
			}
			if(num == 0 ){
				state.centervolumeinfo = []
		 		location.href='#/cart2/center/'+state.cart2No
			}else {
				dispatch('centerprivate', arr)
			}
			
			// console.log(num)
		},
		Centercart2No ({dispatch, commit, state, rootState }, options) {
			 state.cart2No = options
		},
		Alldata ({dispatch, commit, state, rootState }, options) {
			 state.Alldata = options
		},
		centerAlldata ({dispatch, commit, state, rootState }, options) {
			 state.centerAlldata = options
		},
		// 券列表查询
		volumeSave ({dispatch, commit,state, rootState }) {
			let params = {
				app: 'wap',
				appVersion: '3.2.2',
				cityId: rootState.position.cityCode,
			}
			fetch({
				url: tps + '/app/cardcoupon/private/queryCouponListInfo.do',
				params: params,
				jsonp: 'callBack'
			}).then((rep) => {
				 	if(rep.code==1){
						 var data = rep.data;
						 if(!data) return;
						 if(data.bestCouponInfoList) {
						 		var arr = [];
						 		for(var i = 0; i < data.bestCouponInfoList.length; i++) {
						 			arr.push({"couponNo": data.bestCouponInfoList[i].couponNumber})
						 		}
							 	 dispatch('private1', arr)
						 }
						 if(data.couponList) {
						 	state.couponList = data.couponList;//优惠卷的列表
						 }

						 if(!data.bestCouponInfoList && !data.couponList) {
						 	state.volumeinfo = []
							state.couponList = []
						 }
					}else{
						AlertBox({type: 'mini',msg: rep.msg})
					}
			});
			
		},
		// 购物车2券保存
		centerprivate ({dispatch, commit,state, rootState }, options){
				fetch({
					url: shop + '/xd-cart-web/cloud/cardcoupon/private/recCouponInfo.do',
					params: {
						cart2No: state.cart2No,
						useCouponList: JSON.stringify(options),
						verificationCode:''
					},
					type:'post'
				}).then((rep) => {
					if(rep.code==1){
						if(rep.data && rep.data.usedCouponInfos && rep.data.usedCouponInfos.length > 0) {
						 	state.centervolumeinfo = rep.data.usedCouponInfos
						 	if(rep.data.errorInfos && rep.data.errorInfos.length > 0) {
						 		AlertBox({type: 'mini',msg: rep.data.errorInfos[0].errorMessage})
						 	}
						}else {
							state.centervolumeinfo = []
						}
						
				 		location.href='#/cart2/center/'+state.cart2No
					 
					}else{
						AlertBox({type: 'mini',msg: rep.msg})
					}
				});
		},
		private1({dispatch, commit,state, rootState }, options){
				
				fetch({
					url: tps + '/app/cardcoupon/private/recCouponInfo.do',
					params: {
						app: 'wap',
						appVersion: '3.2.2',
						cityId: rootState.position.cityCode,
						data: JSON.stringify(options)
					},
					type:'post'
				}).then((rep) => {
					if(rep.code==1){
							// commit('updateFromCoupon', true)
							// location.href="#/cart2"	
						 	dispatch('getCart2', 1)
					}else{
						AlertBox({type: 'mini',msg: rep.msg})
					}
				});
		}, 
 

		// 设置默认收货地址
		setAddress ({dispatch, commit,state, rootState }) {
			/**
			 * 判断state中是否有默认地址，没有则取当前poiId下面的地址
			 * 
			 */
			 //if(state.volumeinfo.length == 0){
				var recDelivery = function(addressId){
					fetch({
						url: `${tps}/app/cart2/private/confirmAddress.do`,
						params: {
							app: 'wap',
							appVersion: '3.2.2',
							cityId: rootState.position.cityCode,
							areaId: rootState.position.areaId,
							data: JSON.stringify({
								"storeCode": rootState.position.storeLocation,
								"storeChangeFlah": "0",
								"addressId": addressId.toString(),
								"areaId": rootState.position.areaId,
								"poiId": rootState.position.poiId
							})
						},
						type: 'post'
					}).then(res => {
						
							dispatch('volumeSave')
							dispatch('getCart2')
							
						
						if (res.code == '1') {
							commit('updateInvalidItems2', null);
						}
						else {
							commit('updateInvalidItems2', res.data.errorInfos);
						}
					})
				}
			

				if(rootState.defaultAddress.addressId){
					recDelivery(rootState.defaultAddress.addressId)
				}else{
					fetch({
						url: `${mdm}/cmwsmdm-web/address/getAddressByPoi.do?poiId=${rootState.position.poiId}`,
						params: {}
					}).then(res => {
						if ( res.code !='1'|| !res.data.userAddressInfo ){
								dispatch('getCart2')
							return
						}
						let info = res.data.userAddressInfo;
						recDelivery(info.addressId)
						commit('setDefaultAddress', {addressId: info.addressId})
					})
				}
			//}
			 
		}

		// 小店车2去付款
		,goPay ({state, commit, dispatch, rootState }, {type, time, remarks, isPickUp, pickUpInfo}) {
			var pickUp = 0
			var arrivalTime = ''
			var pickUpId = ''
			var pickUpAddress  = ''
			var pickUpPhone  = ''
			let arrivalType = type
			if(!isPickUp){
				arrivalTime = time.join(' ')
			}else{
				if(!pickUpInfo.pickUpDate){
					AlertBox({
						type: 'mini',
						delay: 1500,
						msg: '请选择自提时间'
					})
					return;
				}
				pickUp = 1
				arrivalTime = pickUpInfo.pickUpDate
				pickUpId = pickUpInfo.pickUpId
				pickUpAddress  = pickUpInfo.pickUpAddress
				pickUpPhone  = pickUpInfo.pickUpTel
				arrivalType = 3
			}
			
			
			let params = {

				app: 'wap',
				appVersion: '3.2.2',
				cityId: rootState.position.cityCode,
				isPickUp: pickUp,
				operationStoreCode: rootState.position.storeLocation,
				orderMemoJson: remarks,
				orderSource: 'wap',
				payType: '01',
				selectStrategy: arrivalType,
				selectedArrivalTime: arrivalTime,
				pickUpId: pickUpId,
				pickUpAddress: pickUpAddress,
				pickUpPhone: pickUpPhone,
				poiId: rootState.position.poiId,
				areaId: rootState.position.areaId
			}

			fetch({
				url: tps + '/app/cart2/private/submitOrder.do',
				params: params,
				type: 'post'
			}).then((json) => {
				if(json.code==1){
					commit('updateInvalidItems2', null);
					//跳转
					// 如果全额优惠券支付，直接跳车4
					if(json.data.cartHeadInfo.isCouponAllPay&&json.data.cartHeadInfo.isCouponAllPay==1){
						router.push('/cart4/'+json.data.cartHeadInfo.orderId)
					}else{
						router.push('/cart3/'+json.data.cartHeadInfo.orderId)
					}
				}else{
					if (json.data.errorInfos && json.data.errorInfos.length) {
						commit('updateInvalidItems2', json.data.errorInfos);											
					}
					else {
						AlertBox({type: 'mini',msg: json.msg})
						state.cart2Info.deliveryInfo.canPickUp&&dispatch('storeStationList');
						//dispatch('setAddress')
					}
				}
			});
		}
		// 中心仓购物车去付款
		,centerGoPay({ commit, dispatch, rootState }, orderId){
			 // 去支付
            commit('showMask', true)
            let params = {
                cart2No: orderId,
                deviceNo: 'wap',
				POI: rootState.position.poiId
            }
            fetch({
                url: shop + '/xd-cart-web/cloud/cart2/submitOrder.do',
                params: params,
                type: 'post'
            }).then((info) => {
                console.log(info)
                if(info.code==1){
                    if(info.data.cartHeadInfo.isSuccess=='N'){
                        AlertBox({type:'mini', msg:info.data.errorInfos[0].errorMessage})
						commit('showMask', false)
                    }

                    let orderId = info.data.orderItems[0].orderInfo.orderId;

					// 如果全额优惠券支付，直接跳车4
					if(info.data.cartHeadInfo.isCouponAllPay&&info.data.cartHeadInfo.isCouponAllPay==1){
						router.push('/cart4/'+orderId)
					}
					else {
						// 调用OFS接口跳转到支付中台
                    	dispatch('OFStoPay', orderId)
					}
                }else if(info.code=='SYS-20-01-0000'){
                    router.push('/order')
                }else{
					 AlertBox({type:'mini', msg:info.msg})
                }
            }).then((info) => {

                
            });
		}
		// 中心仓购物车去付款
		,OFStoPay({ commit, rootState }, orderId){
			// 调用OFS接口跳转到支付中台
			var postUrl = order + '/wap/pay/toPay.do';
			var ExportForm = document.createElement("FORM");  
			document.body.appendChild(ExportForm);  
			ExportForm.method = "GET";

			var inputData = [{
					name: 'orderId',
					value: orderId
				},{
					name: 'deviceInfo',
					value: ''
				},{
					name: 'payFlag',
					value: '1'
				},{
					name: 'wapCustomUrl',
					value: `${location.origin}/#/cart4/center/${orderId}`
				}]

			for(let i =0; i<inputData.length; i++){
				var newElement = document.createElement("input");  
				newElement.value = inputData[i].value;
				newElement.setAttribute("name", inputData[i].name);  
				newElement.setAttribute("type", "hidden");
				ExportForm.appendChild(newElement);   
			}
			
			ExportForm.action = postUrl;
			ExportForm.submit();  
		}
	},

	getters: {
		cart2Info: (state, getters, rootState) => {
			let data = {
				// 时间选择
				deliveryInfo: {},
				cartHeadBasicInfo: {},
				deliveryList: []
			}
			//debugger
			if(state.cart2Info){
				// 封装时间选择
				state.cart2Info.arrivalTimeInfos.forEach((ov, oi)=>{
					// 存入一级目录
					data.deliveryList.push({
						'name': ov.date+' '+ov.desc,
						'value': ov.date,
						'parent': 0
					})
					// 存入二级目录
					ov.selectTimes.forEach((tv, ti)=>{
						data.deliveryList.push({
							name: oi==0&&ti==0&&tv.flag==0?'一小时达':tv.time,
							value: oi+'-'+ti,
							parent: ov.date,
							flag: tv.flag
						})
					})
				})
				data.deliveryInfo = state.cart2Info.deliveryInfo;
				data.cartHeadBasicInfo = state.cart2Info.cartHeadBasicInfo;
				data.cmmdtyInfoItems = state.cart2Info.cmmdtyInfoItems;
				data.shopInfo = state.cart2Info.shopInfo;
			}
			return data
		},
		volumeinfo: (state, getters, rootState) => {
			var data;
			var rmb = 0;

			if(state.volumeinfo.length > 0) {
				for(var i = 0; i < state.volumeinfo.length; i++) {
					rmb += +state.volumeinfo[i].usedAmount
				}
				data = `已使用${state.volumeinfo.length}张优惠券,节省了<span>${parseFloat(rmb).toFixed(2)}</span>元`
			}else {
					var ableNum = 0;
					for(let i = 0; i< state.couponList.length; i++) {
						if(state.couponList[i].usefulFlag == 1) {
							ableNum ++ 
						}	
					}

					data = ableNum == 0? `没有可用优惠券` : `<span class="enable_volume">${ableNum}张优惠券</span>`
 
			}
			return data;
		},
		centervolumeinfo: (state, getters, rootState) => {
			var rmb = 0;
			 for(var i =0; i < state.centervolumeinfo.length; i++ ){
			 	rmb += +state.centervolumeinfo[i].usedAmount
			 }
			 var data = '已使用'+state.centervolumeinfo.length+'张优惠券 节省<span>'+parseFloat(rmb).toFixed(2)+'</span>元'
			 return data;
		}
	}
}

